package com.stn.zjx.givingtreasure.activity.userwallet;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.came.viewbguilib.ButtonBgUi;
import com.google.gson.Gson;
import com.jungly.gridpasswordview.GridPasswordView;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.activity.set.ForgetPayPassActivity;
import com.stn.zjx.givingtreasure.activity.set.PayPasswordSetActivity;
import com.stn.zjx.givingtreasure.activity.set.UserPhoneBindActivity;
import com.stn.zjx.givingtreasure.activity.userbankcard.AddUserBankCardActivity;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.bean.BankCard;
import com.stn.zjx.givingtreasure.domain.BankCardDomain;
import com.stn.zjx.givingtreasure.domain.GetUserMoneyDomain;
import com.stn.zjx.givingtreasure.domain.PayConfigDomain;
import com.stn.zjx.givingtreasure.domain.StatusDomain;
import com.stn.zjx.givingtreasure.event.BankCardEvent;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.impl.PayNetImpl;
import com.stn.zjx.givingtreasure.net.impl.UserBankCardNetImpl;
import com.stn.zjx.givingtreasure.net.impl.UserMoneyIntegralImpl;
import com.stn.zjx.givingtreasure.service.UserService;
import com.stn.zjx.givingtreasure.table.User;
import com.stn.zjx.givingtreasure.widget.VirtualKeyboardView;
import com.vondear.rxtools.RxActivityTool;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

public class UserWithDrawActivity extends BaseActivity {


    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.action_title)
    TextView actionTitle;
    @BindView(R.id.web_title)
    TextView webTitle;
    @BindView(R.id.action_add_bt)
    RelativeLayout actionAddBt;
    @BindView(R.id.action_refresh)
    RelativeLayout actionRefresh;
    @BindView(R.id.exit)
    RelativeLayout exit;
    @BindView(R.id.sure_bt)
    TextView sureBt;
    @BindView(R.id.skip_bt)
    TextView skipBt;
    @BindView(R.id.share_bt)
    RelativeLayout shareBt;
    @BindView(R.id.more_bt)
    RelativeLayout moreBt;
    @BindView(R.id.scan_bt)
    RelativeLayout scanBt;
    @BindView(R.id.release_bt)
    ButtonBgUi releaseBt;
    @BindView(R.id.search_iv)
    ImageView searchIv;
    @BindView(R.id.search_edit)
    EditText searchEdit;
    @BindView(R.id.search_bg)
    RelativeLayout searchBg;
    @BindView(R.id.save_bt)
    TextView saveBt;
    @BindView(R.id.avatar_civ)
    CircleImageView avatarCiv;
    @BindView(R.id.user_nickname)
    TextView userNickname;
    @BindView(R.id.user_sex)
    ImageView userSex;
    @BindView(R.id.uuId)
    TextView uuId;
    @BindView(R.id.go_profie)
    RelativeLayout goProfie;
    @BindView(R.id.account_ll)
    LinearLayout accountLl;
    @BindView(R.id.delete_bt)
    RelativeLayout deleteBt;
    @BindView(R.id.money_edit)
    EditText moneyEdit;
    @BindView(R.id.use_money)
    TextView useMoney;
    @BindView(R.id.go_withdraw_bt)
    ButtonBgUi goWithdrawBt;
    @BindView(R.id.bank_card_iv)
    ImageView bankCardIv;
    @BindView(R.id.bank_card_name)
    TextView bankCardName;
    @BindView(R.id.bank_card_no)
    TextView bankCardNo;
    @BindView(R.id.tip_bank_card)
    RelativeLayout tipBankCard;
    BankCard bankCard;
    @BindView(R.id.finish_bt)
    TextView finishBt;
    @BindView(R.id.go_select_bank_card_bt)
    RelativeLayout goSelectBankCardBt;
    @BindView(R.id.fee)
    TextView fee;

    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSelctBankCard(BankCardEvent event) {
        switch (event.flag) {
            case BankCardEvent.Select_Bank_Card:
                if (event.bankCard != null) {
                    bankCard = event.bankCard;
                    Glide.with(UserWithDrawActivity.this)
                            .asBitmap()
                            .load(bankCard.getUserBankCardLogo())
                            .into(new SimpleTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                    bankCardIv.setImageBitmap(resource);
                                }
                            });

                    bankCardName.setText(bankCard.getUserBankCardName());
                    if (bankCard.getUserBankCardNo().length() > 4) {
                        bankCardNo.setText(getString(R.string.dialog_bank_card_modfiy_c2) +
                                bankCard.getUserBankCardNo().substring(bankCard.getUserBankCardNo().length() - 4, bankCard.getUserBankCardNo().length())
                                + " " + bankCard.getUserBankCardType());
                    } else {
                        bankCardNo.setText(getString(R.string.dialog_bank_card_modfiy_c2) +
                                bankCard.getUserBankCardNo() + " " + bankCard.getUserBankCardType());
                    }

                }
                break;
        }
    }


    @Override
    public void initComponent() {
        actionTitle.setText(getString(R.string.withdraw));

        moneyEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (TextUtils.isEmpty(moneyEdit.getText().toString().trim())) {
                    goWithdrawBt.setAlpha(0.4f);
                    goWithdrawBt.setClickable(false);
                    deleteBt.setVisibility(View.GONE);
                } else {
                    goWithdrawBt.setAlpha(1.0f);
                    goWithdrawBt.setClickable(true);
                    deleteBt.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        deleteBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                moneyEdit.getText().clear();
            }
        });

        goWithdrawBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (bankCard == null) {
                    showToast(getString(R.string.please_select_bank_card));
                    return;
                }

                try {
                    if (TextUtils.isEmpty(moneyEdit.getText().toString())) {
                        showToast(getString(R.string.money_is_not_null));
                        return;
                    }
                    if (Double.parseDouble(moneyEdit.getText().toString()) < 0.01) {
                        showToast(getString(R.string.money_not_is_zero));
                        return;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    showToast(getString(R.string.money_not_is_num));
                    return;
                }

                isCheckJoinPassword();
            }
        });

        goWithdrawBt.setClickable(false);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_withdraw);
        ButterKnife.bind(this);
        initComponent();
        initGetBankCard();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBankCardEvent(BankCardEvent event) {
        switch (event.flag) {
            case BankCardEvent.WithDraw:
                initGetBankCard();
                break;
        }
    }

    @OnClick({R.id.back_bt, R.id.tip_bank_card, R.id.go_select_bank_card_bt})
    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.go_select_bank_card_bt:
                if (bankCard == null) {
                    return;
                }
                bundle.putInt("userBankCardId", bankCard.getUserBankCardId());
                RxActivityTool.skipActivity(this, UserSelectBankCardActivity.class, bundle);
                break;
            case R.id.back_bt:
                finish();
                break;
            case R.id.tip_bank_card:

                bundle.putInt("flag", BankCardEvent.WithDraw);
                RxActivityTool.skipActivity(this, AddUserBankCardActivity.class, bundle);
                break;

        }
    }


    public void getMoney() {
        User onlineUser = UserService.getInstance(this).getOnlineLoginUser();
        if (onlineUser == null) {
            return;
        }
        UserMoneyIntegralImpl.get_money(onlineUser.getToken(), onlineUser.getToken() + "_get_money", new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (response.isSuccessful() && !isFinishing()) {
                    initMoney(response.body());
                }
            }

            @Override
            public void onCacheSuccess(Response<String> response) {
                super.onCacheSuccess(response);
                if (response.isSuccessful() && !isFinishing()) {
                    initMoney(response.body());
                }
            }
        });
    }

    @SuppressLint("SetTextI18n")
    public void initMoney(String body) {
        GetUserMoneyDomain domain = new Gson().fromJson(body, GetUserMoneyDomain.class);
        switch (domain.getStatus()) {
            case BaseApi.REQUEST_SUCCESS_CODE:
                try {
                    DecimalFormat decimalFormat = new DecimalFormat("0.00");
                    useMoney.setText(getString(R.string.use_money) + " " + decimalFormat.format(domain.getData().getUserMoney()) + "" + getString(R.string.rmb));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        getMoney();
        get_user_balance_config();
    }


    public void isCheckJoinPassword() {
        if (UserService.getInstance(this).getOnlineLoginUser() == null) {
            return;
        }
        PayNetImpl
                .join_set_user_paypassword(UserService.getInstance(this).getOnlineLoginUser().getToken(),
                        "join_set_user_paypassword", new StringCallback() {
                            @Override
                            public void onStart(Request<String, ? extends Request> request) {
                                super.onStart(request);
                                showLoading();
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();
                                dissmissLoading();
                            }

                            @Override
                            public void onSuccess(Response<String> response) {
                                StatusDomain domain = new Gson().fromJson(response.body(), StatusDomain.class);
                                switch (domain.getStatus()) {
                                    case BaseApi.REQUEST_SUCCESS_CODE:
                                        RxActivityTool.skipActivity(getApplicationContext(), PayPasswordSetActivity.class);
                                        break;
                                    case BaseApi.REQUEST_ChECK_PAY_PASSWORD_CODE:
                                        initPayDialog();
                                        break;
                                    default:
                                        showToast(domain.getMessage());
                                        break;
                                }

                            }
                        });

    }


    public void initPayDialog() {
        Dialog pay_dialog;
        GridPasswordView gridPasswordView;
        VirtualKeyboardView virtualKeyboardView;
        GridView gridView;
        LinearLayout under;
        pay_dialog = new Dialog(this, R.style.dialog_soft_input);
        pay_dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        pay_dialog.setContentView(R.layout.dialog_input_pay_password);
        WindowManager.LayoutParams lp = pay_dialog.getWindow().getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;
        pay_dialog.getWindow().setAttributes(lp);
        View close = pay_dialog.findViewById(R.id.close);
        pay_dialog.getWindow().setWindowAnimations(R.style.myDialogStyle);
        TextView forgetpassword_bt = pay_dialog.findViewById(R.id.forgetpassword_bt);
        gridPasswordView = pay_dialog.findViewById(R.id.grid_password_edit);
        gridPasswordView.mInputView.setFocusable(false);
        gridPasswordView.mInputView.setFocusableInTouchMode(false);
        virtualKeyboardView = pay_dialog.findViewById(R.id.virtualKeyboardView);
        gridView = pay_dialog.findViewById(R.id.gv_keybord);
        gridPasswordView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        pay_dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
//                // 获取焦点
//                gridPasswordView.requestFocus();
//                SoftInputUtils.openSoftInput(UserTransferActivity.this, pay_dialog.getCurrentFocus());
            }
        });
        pay_dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                gridPasswordView.clearPassword();
//                gridPasswordView.requestFocus();
//                SoftInputUtils.closedSoftInput(UserTransferActivity.this);
            }
        });


        forgetpassword_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                User user = UserService.getInstance(getApplicationContext())
                        .getOnlineLoginUser();
                if (user == null) {
                    return;
                }
                if (TextUtils.isEmpty(user.getUserPhone())) {
                    RxActivityTool.skipActivity(getApplicationContext(), UserPhoneBindActivity.class);
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString("phone", user.getUserPhone());
                    RxActivityTool.skipActivity(getApplicationContext(), ForgetPayPassActivity.class, bundle);
                }

            }
        });
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                pay_dialog.dismiss();
            }
        });


        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                if (position < 11 && position != 9) {    //点击0~9按钮
                    if (gridPasswordView.getPassWord().length() < 6) {
                        gridPasswordView.setPassword(gridPasswordView.getPassWord() + virtualKeyboardView.getValueList().get(position).get("name"));
                    }
                    if (gridPasswordView.getPassWord().length() == 6) {
                        User onlineUser = UserService.getInstance(UserWithDrawActivity.this).getOnlineLoginUser();
                        if (onlineUser == null) {
                            return;
                        }
                        user_balance_withdraw(
                                onlineUser.getToken(),
                                bankCard.getUserRealName(),
                                bankCard.getUserPhone(),
                                bankCard.getUserIdCard(),
                                bankCard.getUserBankCardName(),
                                bankCard.getUserBankCardNo(),
                                bankCard.getUserId(),
                                moneyEdit.getText().toString().trim(),
                                gridPasswordView.getPassWord(),
                                pay_dialog

                        );
                    }
                } else {
                    if (position == 11) {      //点击退格键
                        if (gridPasswordView.getPassWord().length() > 0) {
                            gridPasswordView.setPassword(gridPasswordView.getPassWord().substring(0, gridPasswordView.getPassWord().length() - 1));
                        }
                    }
                }
            }
        });

        pay_dialog.show();
    }


    public void initGetBankCard() {
        User onlineUser = UserService.getInstance(this)
                .getOnlineLoginUser();
        if (onlineUser == null) {
            return;
        }
        UserBankCardNetImpl.query_bank_card_by_user_id(onlineUser.getToken(), onlineUser.getToken() + "_query_bank_card_by_user_id", new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (response.isSuccessful() && !isFinishing()) {
                    initBankCard(response.body());
                }
            }

            @Override
            public void onCacheSuccess(Response<String> response) {
                super.onCacheSuccess(response);
                if (response.isSuccessful() && !isFinishing()) {
                    initBankCard(response.body());
                }
            }
        });
    }

    @SuppressLint("SetTextI18n")
    public void initBankCard(String body) {
        BankCardDomain domain = new Gson().fromJson(body, BankCardDomain.class);
        switch (domain.getStatus()) {
            case BaseApi.REQUEST_SUCCESS_CODE:
                if (domain.getData() != null && domain.getData().size() != 0) {
                    tipBankCard.setVisibility(View.GONE);
                    bankCard = domain.getData().get(0);

                    Glide.with(UserWithDrawActivity.this)
                            .asBitmap()
                            .load(bankCard.getUserBankCardLogo())
                            .into(new SimpleTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                    bankCardIv.setImageBitmap(resource);
                                }
                            });

                    bankCardName.setText(bankCard.getUserBankCardName());
                    if (bankCard.getUserBankCardNo().length() > 4) {
                        bankCardNo.setText(getString(R.string.dialog_bank_card_modfiy_c2) +
                                bankCard.getUserBankCardNo().substring(bankCard.getUserBankCardNo().length() - 4, bankCard.getUserBankCardNo().length())
                                + " " + bankCard.getUserBankCardType());
                    } else {
                        bankCardNo.setText(getString(R.string.dialog_bank_card_modfiy_c2) +
                                bankCard.getUserBankCardNo() + " " + bankCard.getUserBankCardType());
                    }

                } else {
                    bankCardIv.setImageDrawable(null);
                    bankCardName.setText("");
                    bankCardNo.setText("");
                    bankCard = null;
                    tipBankCard.setVisibility(View.VISIBLE);
                }
                break;
            default:
                bankCardIv.setImageDrawable(null);
                bankCardName.setText("");
                bankCardNo.setText("");
                bankCard = null;
                tipBankCard.setVisibility(View.VISIBLE);
                break;
        }
    }


    public void user_balance_withdraw(String token,
                                      String userRealName,
                                      String userPhone,
                                      String userIdCard,
                                      String userBankCardName,
                                      String userBankCardNo,
                                      Integer userId,
                                      String userMoney,
                                      String userPrivatepwd,
                                      Dialog dialog) {
        dialog.dismiss();
        PayNetImpl
                .user_balance_withdraw(token,
                        userRealName,
                        userPhone,
                        userIdCard,
                        userBankCardName,
                        userBankCardNo,
                        userId,
                        userMoney,
                        userPrivatepwd,
                        token + "_user_balance_withdraw",
                        new StringCallback() {
                            @Override
                            public void onStart(Request<String, ? extends Request> request) {
                                super.onStart(request);
                                showLoading();
                            }

                            @Override
                            public void onFinish() {
                                super.onFinish();
                                dissmissLoading();
                            }

                            @Override
                            public void onSuccess(Response<String> response) {
                                StatusDomain domain = new Gson().fromJson(response.body(), StatusDomain.class);
                                switch (domain.getStatus()) {
                                    case BaseApi.REQUEST_SUCCESS_CODE:
                                        finish();
//                                        moneyEdit.getText().clear();
//                                        getMoney();
//                                        showToast(domain.getMessage());
                                        break;
                                    default:
                                        showToast(domain.getMessage());
                                        break;
                                }
                            }
                        });
    }


    public void get_user_balance_config() {


        PayNetImpl.get_user_balance_config("get_user_balance_config", new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (response.isSuccessful() && !isFinishing()) {
                    PayConfigDomain domain = new Gson().fromJson(response.body(), PayConfigDomain.class);
                    switch (domain.getStatus()){
                        case BaseApi.REQUEST_SUCCESS_CODE:
                            fee.setText(getString(R.string.fee)+domain.getData().getUserWithdrawFee()+"%"+"(最低"+domain.getData().getUserWithdrawFeeOnce()+"元)");
                            break;
                    }

                }
            }

            @Override
            public void onCacheSuccess(Response<String> response) {
                super.onCacheSuccess(response);
                if (response.isSuccessful() && !isFinishing()) {
                    PayConfigDomain domain = new Gson().fromJson(response.body(), PayConfigDomain.class);
                    switch (domain.getStatus()){
                        case BaseApi.REQUEST_SUCCESS_CODE:
                            fee.setText(getString(R.string.fee)+domain.getData().getUserWithdrawFee()+"%"+"(最低"+domain.getData().getUserWithdrawFeeOnce()+"元)");
                            break;
                    }

                }
            }
        });


    }


}
